package cn.dida.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONArray;
import cn.dida.exception.BizzException;
import cn.dida.model.HttpResponseBodyWrapper;
import cn.dida.model.Pageable;
import cn.dida.model.SalesNewMan;
import cn.dida.model.Salesman;
import cn.dida.model.SalesmanSaleHistory;
import cn.dida.model.UserSession;
import cn.dida.service.SalesmanService;
import cn.dida.util.DateUtils;
import cn.dida.util.ExcelUtil;

import com.alibaba.fastjson.JSONObject;

/**
 * 促销员管理
 * @author Administrator weiwei
 */
//@Controller
@Controller
public class SalesmanController extends BaseController {
    @Autowired
    private SalesmanService salesmanService;

    
    /**
     * 促销员列表
     * @param request
     * @param keyword 查询条件
     * @param state 促销员状态：1正常，2注销
     * @param page 分页游标
     * @return ModelAndView 促销员列表页面
     * @throws Exception
     */
    @GetMapping("/salesman")
    public ModelAndView salesman(HttpServletRequest request, String keyword, String branchkeyword, String adname, Integer state, Integer page) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);

        page = (page == null || page < 1) ? 1 : page;
        keyword = StringUtils.trimToNull(keyword);

        Pageable<SalesNewMan> salesmanList = salesmanService.querySalesman(userSession.getCompanyId(), keyword, branchkeyword,adname,state, page);
        model.put("salesmanList", salesmanList);
        model.put("keyword", keyword);
        model.put("branchkeyword", branchkeyword);
        model.put("adname", adname);
        model.put("state", state);
        return new ModelAndView("salesman_list").addAllObjects(model);
    }

    /**
     * 促销员数据导出
     * @param request
     * @param response
     * @param keyword 查询条件
     * @param state 促销员状态：1正常，2注销
     * @return 
     * @throws Exception
     */
    @GetMapping("/salesman/export")
    public ModelAndView salesman_export(HttpServletRequest request, HttpServletResponse response, String keyword, String branchkeyword, String adname, Integer state) throws Exception {
        UserSession userSession = getUserSession(request);
        Map<String, Object> paramMap = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(keyword)) {//网点名称
            paramMap.put("keyword", keyword);
        }
        if (state != null) {
            paramMap.put("state", state);
        }

        List<SalesNewMan> exportList = salesmanService.querySalesmanForExport(userSession.getCompanyId(), keyword,branchkeyword,adname, state);

        String fileName = "促销员数据导出" + DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(exportList.size());

        Map<String, Object> fmap = null;
        for (SalesNewMan obj : exportList) {
            fmap = new HashMap<String, Object>();
            Long tid = NumberUtils.toLong(obj.getId().toString(), 0L);
            fmap.put("code", obj.getCode());
            fmap.put("name", obj.getName());
            fmap.put("phone", obj.getPhone());
            fmap.put("branchname", obj.getBranchname());
            fmap.put("adname", obj.getAdname());
            if (obj.getState() == 1) {
                fmap.put("state", "正常");
            } else if (obj.getState() == 2) {
                fmap.put("state", "注销");
            }
            fmap.put("psnname", obj.getPsnname());
            list.add(fmap);
        }
        String columnNames[] = {"编号", "促销员姓名", "手机号", "门店名称", "门店所在地","负责业务员", "状态"};//列名
        String keys[] = {"code", "name", "phone", "branchname", "adname","psnname", "state"};//map中的key
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
                bos.flush();
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }

        return null;
    }

    /**
     * 促销员列表
     * @param request
     * @param keyword 查询条件
     * @param state 促销员状态：1正常，2注销
     * @return HttpResponseBodyWrapper 封装促销员列表数据
     * @throws Exception
     */
    @ResponseBody
    @GetMapping(value = "/salesman", produces = MediaType.APPLICATION_JSON_VALUE)
    public HttpResponseBodyWrapper getSalesman(HttpServletRequest request, String keyword, Integer state, Integer page) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);
        List<Salesman> salesmanList = salesmanService.querySalesman(userSession.getCompanyId(), state);
        model.put("salesmanList", salesmanList);
        return new HttpResponseBodyWrapper(salesmanList);
    }

    /**
     * 新增促销员
     * @param request
     * @param salesman 促销员实体类
     * @return HttpResponseBodyWrapper 封装操作标记（ true新增成功，false新增失败）
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/salesman")
    public HttpResponseBodyWrapper postSalesman(HttpServletRequest request, @RequestBody Salesman salesman) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);

        salesman.setCompanyId(userSession.getCompanyId());
        salesman.setName(StringUtils.trimToNull(salesman.getName()));
        salesman.setPhone(StringUtils.trimToNull(salesman.getPhone()));
        salesman.setPosition(StringUtils.trimToNull(salesman.getPosition()));
        salesman.setPsnname(StringUtils.trimToNull(salesman.getPsnname()));

        if (salesman.getName() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入销售员姓名");
        }
        if (salesman.getPhone() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入销售员手机号");
        }
        if (salesman.getPsnname() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入负责业务员名称");
        }
        if (salesman.getDepartmentId() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请选择部门");
        }
        if (salesman.getPosition() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入职位名称");
        }
        if (!Pattern.matches("\\d{11}", salesman.getPhone())) {
            throw new BizzException(BizzException.error_code_invalid_params, "手机号输入有误");
        }
        if (salesmanService.getSalesmanByPhone(userSession.getCompanyId(), salesman.getPhone()) != null) {
            throw new BizzException(BizzException.error_code_invalid_params, "已存在手机号为【" + salesman.getPhone() + "】的促销员");
        }

        Boolean result = salesmanService.insertSalesman(salesman);
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 获取促销员信息
     * @param request
     * @param id 促销员id
     * @return HttpResponseBodyWrapper 封装单个促销员实体数据
     * @throws Exception
     */
    @ResponseBody
    @GetMapping("/salesman/{id}")
    public ModelAndView getSalesman(HttpServletRequest request, @PathVariable Integer id) throws Exception {
    	Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);
        SalesNewMan result = salesmanService.getSalesman(userSession.getCompanyId(), id);
        model.put("result", result);
        return new ModelAndView("salesman_detail").addAllObjects(model);
    }
    /**
     * 更新促销员
     * @param request
     * @param salesman 促销员实体信息
     * @return HttpResponseBodyWrapper 封装操作标记（ true更新成功，false更新失败）
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/salesman/{id}")
    public HttpResponseBodyWrapper putSalesman(HttpServletRequest request, @RequestBody SalesNewMan salesman) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);

        salesman.setCompanyId(userSession.getCompanyId());
        salesman.setName(StringUtils.trimToNull(salesman.getName()));
        salesman.setPhone(StringUtils.trimToNull(salesman.getPhone()));
        salesman.setAdname(StringUtils.trimToNull(salesman.getAdname()));
        salesman.setPsnname(StringUtils.trimToNull(salesman.getPsnname()));
        
        if (salesman.getName() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入销售员姓名");
        }
        if (salesman.getPhone() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入销售员手机号");
        }
        if (salesman.getPsnname() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入负责业务员名称");
        }
        if (salesman.getAdcode() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "省市县编码为空");
        }
        if (salesman.getAdname() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请选择省市县");
        }
        if (!Pattern.matches("\\d{11}", salesman.getPhone())) {
            throw new BizzException(BizzException.error_code_invalid_params, "手机号输入有误");
        }
        Salesman tmp = salesmanService.getSalesmanByPhone(userSession.getCompanyId(), salesman.getPhone());
        if (tmp != null && tmp.getId().intValue() != salesman.getId()) {
            throw new BizzException(BizzException.error_code_invalid_params, "已存在手机号为【" + salesman.getPhone() + "】的促销员");
        }
        salesman.setApproveTime(new Date());
        salesman.setStaffId(userSession.getId());
        Boolean result = salesmanService.updateSalesman(salesman);
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 删除促销员
     * @param request
     * @param id 促销员id
     * @return HttpResponseBodyWrapper 封装操作标记（ true删除成功，false删除失败）
     * @throws Exception
     */
    @ResponseBody
    @DeleteMapping("/salesman/{id}")
    public HttpResponseBodyWrapper deleteSalesman(HttpServletRequest request, @PathVariable Integer id) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);
        Boolean result = salesmanService.deleteSalesman(userSession.getCompanyId(), id);
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 销售记录列表
     * @param request
     * @param response
     * @param salesmanId 促销员id
     * @param keyword 查询条件
     * @param timeLimitStart 扫码开始时间
     * @param timeLimitEnd 扫码结束时间
     * @param page 分页游标
     * @return ModelAndView 销售记录列表页面
     * @throws Exception
     */
    @GetMapping("/salesman/salehistory")
    public ModelAndView salehistory(HttpServletRequest request, HttpServletResponse response, Integer salesmanId, String keyword, Long timeLimitStart, Long timeLimitEnd, Integer page) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);

        SalesNewMan salesman = salesmanService.getSalesman(userSession.getCompanyId(), salesmanId);

        if (salesman == null) {
            response.sendRedirect("/salesman");
            return null;
        }

        page = (page == null || page < 1) ? 1 : page;
        keyword = StringUtils.trimToNull(keyword);


        if (timeLimitStart == null || timeLimitEnd == null) {
            Calendar now = Calendar.getInstance();
            Calendar sevenDaysAgo = Calendar.getInstance();
            sevenDaysAgo.clear();
            sevenDaysAgo.set(Calendar.YEAR, now.get(Calendar.YEAR));
            sevenDaysAgo.set(Calendar.MONTH, now.get(Calendar.MONTH));
            sevenDaysAgo.set(Calendar.DATE, now.get(Calendar.DATE));
            sevenDaysAgo.add(Calendar.DATE, -7);

            Calendar today = Calendar.getInstance();
            today.clear();
            today.set(Calendar.YEAR, now.get(Calendar.YEAR));
            today.set(Calendar.MONTH, now.get(Calendar.MONTH));
            today.set(Calendar.DATE, now.get(Calendar.DATE));
            today.set(Calendar.HOUR, 23);
            today.set(Calendar.MINUTE, 59);
            today.set(Calendar.SECOND, 59);
            today.set(Calendar.MILLISECOND, 999);

            timeLimitStart = sevenDaysAgo.getTimeInMillis();
            timeLimitEnd = today.getTimeInMillis();
        }
        Pageable<SalesmanSaleHistory> saleHistory = salesmanService.querySaleHistory(salesman.getId(), keyword, timeLimitStart, timeLimitEnd, page);

        model.put("salesman", salesman);
        model.put("saleHistory", saleHistory);
        model.put("keyword", keyword);
        model.put("timeLimitStart", timeLimitStart);
        model.put("timeLimitEnd", timeLimitEnd);
        return new ModelAndView("salesman_salehistory").addAllObjects(model);
    }

    /**
     * 促销员销售记录数据导出
     * @param request
     * @param response
     * @param salesmanId 促销员id
     * @param keyword 查询条件
     * @param timeLimitStart 扫码开始时间
     * @param timeLimitEnd 扫码结束时间
     * @return 
     * @throws Exception
     */
    @GetMapping("/salesman/salehistory/export")
    public ModelAndView salehistory_export(HttpServletRequest request, HttpServletResponse response, Integer salesmanId,
                                           String keyword, Long timeLimitStart, Long timeLimitEnd) throws Exception {

        Map<String, Object> paramMap = new HashMap<String, Object>();

        if (salesmanId != null) {
            paramMap.put("salesmanId", salesmanId);
        }
        if (StringUtils.isNotBlank(keyword)) {
            paramMap.put("keyword", keyword);
        }
        if (timeLimitStart != null) {
            paramMap.put("timeLimitStart", timeLimitStart);
        }
        if (timeLimitEnd != null) {
            paramMap.put("timeLimitEnd", timeLimitEnd);
        }


        List<SalesmanSaleHistory> exportList = salesmanService.querySaleHistoryForExport(salesmanId, keyword, timeLimitStart, timeLimitEnd);

        String fileName = "促销员销售记录数据导出" + DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(exportList.size());

        Map<String, Object> fmap = null;
        for (SalesmanSaleHistory obj : exportList) {
            fmap = new HashMap<String, Object>();
            Long tid = NumberUtils.toLong(obj.getId().toString(), 0L);
            fmap.put("id", tid);
            fmap.put("proName", obj.getProName());
            fmap.put("proBarcode", obj.getProBarcode());
            fmap.put("proNumber", obj.getProNumber());
            fmap.put("cTime", DateUtils.formatTimeInMillis(obj.getcTime()));

            list.add(fmap);
        }
        String columnNames[] = {"ID", "产品名称", "产品条码", "产品编号", "扫码时间"};//列名
        String keys[] = {"id", "proName", "proBarcode", "proNumber", "cTime"};//map中的key
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
                bos.flush();
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }

        return null;
    }
    
    
    /**
     * 手动支付列表
     * @author kelan
     * @date 2017年4月26日
     * @param request
     * @param response
     * @param keyword
     * @param timeLimitStart
     * @param timeLimitEnd
     * @param page
     * @return
     * @throws Exception
     */
    @GetMapping("/payment")
    public ModelAndView salepaymentyList(HttpServletRequest request, HttpServletResponse response, String keyword, Long timeLimitStart, Long timeLimitEnd, Integer page) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);
        Map<String, Object> paramMap = getSimpleRequestParamMap(request);
        page = (page == null || page < 1) ? 1 : page;
        keyword = StringUtils.trimToNull(keyword);
        Pageable<Map<String,Object>> salesmanloglist = salesmanService.querysalepaymentyList(userSession.getCompanyId(), keyword, timeLimitStart, timeLimitEnd, page);
      
        if (null != salesmanloglist && salesmanloglist.getResult().size() > 0) {
			for (int j = 0; j < salesmanloglist.getResult().size(); j++) {
				Map<String, Object> tmap = salesmanloglist.getResult().get(j);
				tmap.put("id", j+1);
			}

		}
        salesmanloglist.setRquesturl(request, paramMap);
        model.put("pagelist", salesmanloglist);
        model.put("keyword", keyword);
        model.put("timeLimitStart", timeLimitStart);
        model.put("timeLimitEnd", timeLimitEnd);
        return new ModelAndView("salesman_payment").addAllObjects(model);
    }
    
    /**
     * 手动支付支付页面
     * @author kelan
     * @date 2017年4月27日
     * @param request
     * @param keyword
     * @param companyname
     * @param price
     * @param product_id
     * @param proname
     * @param procode
     * @param page
     * @return
     * @throws Exception
     */
    @GetMapping("/payment/detail")
    public ModelAndView salepaymentyDetailList(HttpServletRequest request,  String keyword, String companyname, String price,Integer product_id ,String proname,String procode ,Integer page) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);
        page = (page == null || page < 1) ? 1 : page;
        keyword = StringUtils.trimToNull(keyword);
        Pageable<Map<String,Object>> result = salesmanService.querysalepaymentydetailList(userSession.getCompanyId(),keyword,companyname, price, product_id,page);
        
        if(null!=result && result.getResult().size()>0){
        	for (int j = 0; j < result.getResult().size(); j++) {
    			Map<String, Object> tmap = result.getResult().get(j);
    			tmap.put("id", j+1);
//    			tmap.put("sumprice1", String.valueOf(tmap.get("sumprice1")));
    		}
        }
        model.put("pagelist", result);
        model.put("keyword", keyword);
        model.put("companyname", companyname);
        model.put("price", price);
        model.put("product_id", product_id);
        model.put("proname", proname);
        model.put("procode", procode);
        return new ModelAndView("salesman_paydetail").addAllObjects(model);
    }
    
    /**
     * 支付提交
     * @author kelan
     * @date 2017年4月27日
     * @param request
     * @param paymentlist
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PutMapping("/payment/paymentsave")
    public HttpResponseBodyWrapper PaymentlistSave(HttpServletRequest request, @RequestBody Map<String, Object> paymentlist) throws Exception {

    	UserSession userSession = getUserSession(request);
        Boolean result = false;
        System.out.println(paymentlist.toString());
        if(paymentlist.containsKey("List") && paymentlist.containsKey("product_id")){
        	 JSONArray js = JSONArray.parseArray(paymentlist.get("List").toString());
        	 String product_id = paymentlist.get("product_id").toString();
        	 salesmanService.PaymentlistSave(js,product_id);
        }
        
        return new HttpResponseBodyWrapper(result);
    }
    
    /**
     * 已支付列表
     * @author kelan
     * @date 2017年4月28日
     * @param request
     * @param response
     * @param keyword
     * @param timeLimitStart
     * @param timeLimitEnd
     * @param page
     * @return
     * @throws Exception
     */
    @GetMapping("/paymentoff")
    public ModelAndView salepaymentyOffList(HttpServletRequest request, HttpServletResponse response, String keyword, Long timeLimitStart, Long timeLimitEnd, Integer page) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);
        Map<String, Object> paramMap = getSimpleRequestParamMap(request);
        page = (page == null || page < 1) ? 1 : page;
        keyword = StringUtils.trimToNull(keyword);
        Pageable<Map<String,Object>> salesmanloglist = salesmanService.querysalepayoffmentyList(userSession.getCompanyId(), keyword, timeLimitStart, timeLimitEnd, page);
      
        if (null != salesmanloglist && salesmanloglist.getResult().size() > 0) {
			for (int j = 0; j < salesmanloglist.getResult().size(); j++) {
				Map<String, Object> tmap = salesmanloglist.getResult().get(j);
				tmap.put("id", j+1);
			}

		}
        salesmanloglist.setRquesturl(request, paramMap);
        model.put("pagelist", salesmanloglist);
        model.put("keyword", keyword);
        model.put("timeLimitStart", timeLimitStart);
        model.put("timeLimitEnd", timeLimitEnd);
        return new ModelAndView("salesman_paymentoff").addAllObjects(model);
    }
    
    
    /**
     * 已支付详情
     * @author kelan
     * @date 2017年4月28日
     * @param request
     * @param keyword
     * @param companyname
     * @param price
     * @param product_id
     * @param proname
     * @param procode
     * @param page
     * @return
     * @throws Exception
     */
    @GetMapping("/paymentoff/detail")
    public ModelAndView salepaymentyOffDetailList(HttpServletRequest request,  String keyword, String companyname,Integer product_id ,String proname,String procode ,String c_time ,Integer page) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);
        page = (page == null || page < 1) ? 1 : page;
        keyword = StringUtils.trimToNull(keyword);
        Pageable<Map<String,Object>> result = salesmanService.querysalepaymentyoffdetailList(userSession.getCompanyId(),keyword,companyname,product_id,c_time,page);
        
        if(null!=result && result.getResult().size()>0){
        	for (int j = 0; j < result.getResult().size(); j++) {
    			Map<String, Object> tmap = result.getResult().get(j);
    			tmap.put("id", j+1);
    		}
        }
		
        model.put("pagelist", result);
        model.put("keyword", keyword);
        model.put("companyname", companyname);
        model.put("product_id", product_id);
        model.put("proname", proname);
        model.put("procode", procode);
        return new ModelAndView("salesman_payoffdetail").addAllObjects(model);
    }
    
    
    
   	/**
   	 * 促销员未支付数据导出
   	 * @author kelan
   	 * @date 2017年5月5日
   	 * @param request
   	 * @param response
   	 * @param keyword
   	 * @param timeLimitStart
   	 * @param timeLimitEnd
   	 * @return
   	 * @throws IOException
   	 */
   	@GetMapping("/payment/export")
       public String PaymentExport(HttpServletRequest request, HttpServletResponse response, String keyword, Long timeLimitStart, Long timeLimitEnd) throws IOException{
       	
       	UserSession userSession = getUserSession(request);
       	
        //Pageable<Map<String,Object>> salesmanloglist = salesmanService.querysalepaymentyList(userSession.getCompanyId(), keyword, timeLimitStart, timeLimitEnd, page);
       	List<Map<String,Object>> List = new ArrayList<Map<String,Object>> ();
        List<Map<String,Object>> exportList = salesmanService.querySalepaymentyExport(userSession.getCompanyId(),keyword,timeLimitStart,timeLimitEnd);
        
        for (int i=0;i<exportList.size();i++){
        	Map<String,Object> map = exportList.get(i);
        	map.put("id", i);
        	List.add(map);
        }
       	String fileName="促销员未支付数据导出"+DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");
       	String columnNames[] = {"ID","促销员名称","产品名称","数量（瓶）/扫码次数"};//列名
       	String keys[] = {"id","salesname","proname","nubs"};//map中的key
       	ByteArrayOutputStream os = new ByteArrayOutputStream();
       	try {
       		ExcelUtil.createWorkBook(List,keys,columnNames).write(os);
       	} catch (IOException e) {
       		e.printStackTrace();
       	}
       	byte[] content = os.toByteArray();
       	InputStream is = new ByteArrayInputStream(content);
       	// 设置response参数，可以打开下载页面
       	response.reset();
       	response.setContentType("application/vnd.ms-excel;charset=utf-8");
       	response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
       	ServletOutputStream out = response.getOutputStream();
       	BufferedInputStream bis = null;
       	BufferedOutputStream bos = null;
       	try {
       		bis = new BufferedInputStream(is);
       		bos = new BufferedOutputStream(out);
       		byte[] buff = new byte[2048];
       		int bytesRead;
       		// Simple read/write loop.
       		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
       			bos.write(buff, 0, bytesRead);
       			bos.flush();
       		}
       	} catch (final IOException e) {
       		throw e;
       	} finally {
       		if (bis != null)
       			bis.close();
       		if (bos != null)
       			bos.close();
       	}
       	return null;
       }
    
  
   	/**
   	 * 促销员已支付数据导出
   	 * @author kelan
   	 * @date 2017年5月5日
   	 * @param request
   	 * @param response
   	 * @param keyword
   	 * @param timeLimitStart
   	 * @param timeLimitEnd
   	 * @return
   	 * @throws IOException
   	 */
   	@GetMapping("/paymentoff/export")
    public String PaymentOffExport(HttpServletRequest request, HttpServletResponse response, String keyword, Long timeLimitStart, Long timeLimitEnd) throws IOException{
       	UserSession userSession = getUserSession(request);
       	
        //Pageable<Map<String,Object>> salesmanloglist = salesmanService.querysalepaymentyList(userSession.getCompanyId(), keyword, timeLimitStart, timeLimitEnd, page);
       	List<Map<String,Object>> List = new ArrayList<Map<String,Object>> ();
        List<Map<String,Object>> exportList = salesmanService.querySalepaymentOffExport(userSession.getCompanyId(),keyword,timeLimitStart,timeLimitEnd);
        
        for (int i=0;i<exportList.size();i++){
        	Map<String,Object> map = exportList.get(i);
        	map.put("id", i);
        	Integer state = (Integer) map.get("payment_state");
        	if(state == 0){
        		map.put("state", "支付中");
        	}else if(state == 1){
        		map.put("state", "支付成功");
        	}else {
        		map.put("state", "支付失败");
        	}
        	List.add(map);
        }
       	String fileName="促销员已支付数据导出"+DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");
       	String columnNames[] = {"ID","企业号应用ID","促销员OpenID","促销员名称","产品名称","数量（瓶）/扫码次数","每瓶费用","小计","支付状态","付款时间","付款返回信息"};//列名
       	String keys[] = {"id","weixin_appid","weixin_openid","salesname","proname","nubs","product_price","sumprice","state","c_time","weixin_payreturn_msg"};//map中的key
       	ByteArrayOutputStream os = new ByteArrayOutputStream();
       	try {
       		ExcelUtil.createWorkBook(List,keys,columnNames).write(os);
       	} catch (IOException e) {
       		e.printStackTrace();
       	}
       	byte[] content = os.toByteArray();
       	InputStream is = new ByteArrayInputStream(content);
       	// 设置response参数，可以打开下载页面
       	response.reset();
       	response.setContentType("application/vnd.ms-excel;charset=utf-8");
       	response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
       	ServletOutputStream out = response.getOutputStream();
       	BufferedInputStream bis = null;
       	BufferedOutputStream bos = null;
       	try {
       		bis = new BufferedInputStream(is);
       		bos = new BufferedOutputStream(out);
       		byte[] buff = new byte[2048];
       		int bytesRead;
       		// Simple read/write loop.
       		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
       			bos.write(buff, 0, bytesRead);
       			bos.flush();
       		}
       	} catch (final IOException e) {
       		throw e;
       	} finally {
       		if (bis != null)
       			bis.close();
       		if (bos != null)
       			bos.close();
       	}
       	return null;
       }
    
    
    
    /**
     * 红包发送回调更改状态方法
     * @author kelan
     * @date 2017年5月5日
     * @param jsonString
     * @param request
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/callback", produces="application/json;charset=UTF-8")
 	@ResponseBody
	public HttpResponseBodyWrapper updatePaymentState(@RequestBody  String jsonString,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException { 
    	JSONObject js = JSONObject.parseObject(jsonString);
    	boolean result = salesmanService.updatePaymentState(js);
		return new HttpResponseBodyWrapper(true);

	}
}
